package com.the_ring.chapter12;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager2.widget.ViewPager2;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.RectEvaluator;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.the_ring.chapter12.adapter.PictureAdapter;
import com.the_ring.chapter12.widget.MosaicView;
import com.the_ring.chapter12.widget.ShutterView;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements Animator.AnimatorListener {

    private static final String TAG = "MainActivity";

    // 动画类型
    private static final int ANIM_FADE = 0;         // 淡入淡出动画
    private static final int ANIM_ALPHA = 1;        // 灰度动画
    private static final int ANIM_TRANSLATE = 2;    // 平移动画
    private static final int ANIM_SCALE = 3;        // 缩放动画
    private static final int ANIM_ROTATE = 4;       // 旋转动画
    private static final int ANIM_TAILOR = 5;       // 裁剪动画
    private static final int ANIM_SHUTTER = 6;      // 百叶窗动画
    private static final int ANIM_COMBINE = 7;      // 组合动画


    private Animation alphaAnim, translateAnim, scaleAnim, rotateAnim;

    private View preView, curView;  // 播放动画时前一张图和当前图

    private ImageView view1, view4, view5, view6;
    private ShutterView view2;
    private MosaicView view3;
    private ObjectAnimator anim1, anim2, anim3, anim4;
    private int duration = 5000;

    private TextView animTitleTv;
    private RelativeLayout picChoiceRl;    // 图片选择布局
    private RelativeLayout playRl;          // 播放动画布局

    private ImageView tweenAnimIv;
    private List<Integer> imageArray;
    private AnimationSet setAnim;

    private List<String> imageUriList;
    private ActivityResultLauncher<Intent> launcher;    // 选取图片启动器
    private Toolbar headTl;
    private PictureAdapter pictureAdapter;
    private ViewPager2 viewPager2;
    private RadioGroup animTypeRg;
    private int[] animTypes;

    private static final int PLAY = 0;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PLAY:
                    int curPic = msg.arg1;
                    Bitmap bitmap = getBitmap(imageUriList.get(curPic));
                    // TODO 实现动画
                    switch (animTypes[curPic]) {
                        case ANIM_FADE:
                            Drawable[] drawables = {getDrawableFromUri(imageUriList.get(curPic - 1)), getDrawableFromUri(imageUriList.get(curPic))};
                            TransitionDrawable fadeAnim = new TransitionDrawable(drawables);
                            fadeAnim.setCrossFadeEnabled(true);
                            fadeAnim.startTransition(duration);
                            ImageView view = getImageView();
                            view.setImageDrawable(fadeAnim);
                            break;
                        case ANIM_TRANSLATE:
                            break;
                        case ANIM_SCALE:
                            break;
                        case ANIM_ROTATE:
                            break;
                        case ANIM_TAILOR:
                            break;
                        case ANIM_SHUTTER:
                            break;
                        case ANIM_COMBINE:
                            break;
                    }
                    break;
            }
        }
    };

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        headTl = findViewById(R.id.tl_head);
        setSupportActionBar(headTl);
        headTl.setNavigationOnClickListener(v -> finish());

        animTitleTv = findViewById(R.id.tv_anim_title);
        picChoiceRl = findViewById(R.id.rl_pic_choice);
        viewPager2 = findViewById(R.id.vp_picture);
        animTypeRg = findViewById(R.id.rg_anim_type);
        animTypeRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int childCount = group.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    if (group.getChildAt(i).getId() == checkedId) {
                        animTypes[viewPager2.getCurrentItem()] = i;
                        break;
                    }
                }
            }
        });

        playRl = findViewById(R.id.rl_play);


        imageUriList = new ArrayList<>();
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Intent intent = result.getData();
            int code = result.getResultCode();
            if (intent != null) {
                ClipData imageNames = intent.getClipData();
                if (imageNames != null) {
                    imageUriList.clear();
                    for (int i = 0; i < imageNames.getItemCount(); i++) {
                        Uri uri = imageNames.getItemAt(i).getUri();
                        imageUriList.add(uri.toString());
                        Log.i(TAG, "get image uri from album: " + uri.toString());
                    }
                }
            }

            // 获取到图片列表后显示图片
            updateView();
        });
    }

    private void updateView() {
        animTypes = new int[imageUriList.size()]; // 保存选择的动画类型

        pictureAdapter = new PictureAdapter(getSupportFragmentManager(), getLifecycle(), imageUriList);
        viewPager2.setAdapter(pictureAdapter);
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                animTitleTv.setText("请选择第" + (position + 1) + "张图片的动画");
                if (position == 0) {    // 第一张图不允许选择淡入淡出动画
                    animTypeRg.getChildAt(0).setClickable(false);
                }
                ((RadioButton) animTypeRg.getChildAt(animTypes[position])).setChecked(true);
            }
        });


        viewPager2.setVisibility(View.VISIBLE);
        animTypeRg.setVisibility(View.VISIBLE);


    }

    private Bitmap getBitmap(String imageUri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse(imageUri)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, "getBitmap error: " + e.getMessage());
        }
        return bitmap;
    }

    private Drawable getDrawableFromUri(String imageUri) {
        Bitmap bitmap = getBitmap(imageUri);
        BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
        return drawable;
    }

    private ImageView getImageView() {
        ImageView view = new ImageView(this);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(params);
        return view;
    }


    @Override
    public void onAnimationStart(Animator animation) {}

    @Override
    public void onAnimationEnd(Animator animation) {
        Message message = handler.obtainMessage(PLAY);
        message.arg1++;
        handler.sendMessage(message);

        if (animation.equals(anim1)) {
            picChoiceRl.addView(view2, 0);
            // 从指定资源编号的图片文件中获取位图对象
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageArray.get(0));
            int width = view1.getWidth();
            int height = bitmap.getHeight() * width / bitmap.getWidth();
            // 构造一个从四周向中间裁剪的属性动画
            anim2 = ObjectAnimator.ofObject(view1, "clipBounds",
                    new RectEvaluator(), new Rect(0, 0, width, height),
                    new Rect(width / 2, height / 2, width / 2, height / 2));
            anim2.setDuration(duration);
            anim2.addListener(this);
            anim2.start();
        } else if (animation.equals(anim2)) {
            picChoiceRl.removeView(view1);
            picChoiceRl.addView(view3, 0);
            // 构造一个按比率逐步展开的属性动画
            anim3 = ObjectAnimator.ofInt(view2, "ratio", 0, 100);
            anim3.setDuration(duration);
            anim3.addListener(this);
            anim3.start();
        } else if (animation.equals(anim3)) {
            picChoiceRl.removeView(view2);
            picChoiceRl.addView(view4, 0);
            int offset = 5;
            view3.setOffset(offset);
            // 构造一个按按比率展开的属性动画
            anim4 = ObjectAnimator.ofInt(view3, "ratio", 0 - offset, 101 + offset);
            anim4.setDuration(duration);
            anim4.addListener(this);
            anim4.start();
        } else if (animation.equals(anim4)) {
            picChoiceRl.removeView(view3);
            Drawable[] drawables = {getDrawable(imageArray.get(3)), getDrawable(imageArray.get(4))};
            // 创建一个用于淡入淡出动画的过渡图形
            TransitionDrawable fadeTd = new TransitionDrawable(drawables);
            fadeTd.setCrossFadeEnabled(true);           // 启用交叉淡入
            view4.setImageDrawable(fadeTd);             // 设置过渡图形
            fadeTd.startTransition(duration);l
            animTitleTv.setText("正在播放淡入谈出动画");
            // 在延迟若干秒后启动平移动画的播放任务，平移动画跟在淡入淡出动画后面
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                picChoiceRl.addView(view5, 0);
                // 创建一个平移动画
                translateAnim = new TranslateAnimation(0f, -view4.getWidth(), 0f, 0f);
                translateAnim.setDuration(duration);
                translateAnim.setFillAfter(true);
                view4.startAnimation(translateAnim);
                translateAnim.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }, duration);
        }
    }

    @Override
    public void onAnimationRepeat(Animator animation) {}

    @Override
    public void onAnimationCancel(@NonNull Animator animation) {  }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.head, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.choice_picture) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            launcher.launch(intent);

            playRl.setVisibility(View.GONE);
            picChoiceRl.setVisibility(View.VISIBLE);
            // playShutter(imageUriList.get(0));
        } else if (id == R.id.start_play) {
            // TODO 开始播放动画
            playRl.setVisibility(View.VISIBLE);
            picChoiceRl.setVisibility(View.GONE);
            Message message = handler.obtainMessage();
            message.what = PLAY;
            message.arg1 = 0;
            handler.sendMessage(message);
        }
        return super.onOptionsItemSelected(item);
    }

    private void playRotate(String imageUrl) {
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        ImageView view = new ImageView(this);
        curView = view;
        view.setLayoutParams(params);
        view.setImageBitmap(getBitmap(imageUrl));
        view.setScaleType(ImageView.ScaleType.FIT_CENTER);
        playRl.addView(view, 0);
        startSetAnim(view);

    }

    private void playShutter(String imageUrl) {
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        view2 = new ShutterView(this);
        view2.setLayoutParams(params);
        view2.setBitmap(getBitmap(imageUrl));

        view2.setMode(PorterDuff.Mode.DST_OUT);


        picChoiceRl.removeAllViews();
        picChoiceRl.addView(view2, 0);

        ObjectAnimator anim = ObjectAnimator.ofInt(view2, "ratio", 0, 100);
        anim.setDuration(duration);
        anim.start();
    }

    // 开始播放集合动画
    private void startSetAnim(View view) {
        // 灰度动画
        AlphaAnimation alpha = new AlphaAnimation(1.0f, 0.1f);
        alpha.setDuration(duration);
        alpha.setFillAfter(true);

        // 平移动画
        TranslateAnimation translate = new TranslateAnimation(1.0f, -200f, 1.0f, 1.0f);
        translate.setDuration(duration);
        translate.setFillAfter(true);

        // 缩放动画
        ScaleAnimation scale = new ScaleAnimation(1.0f, 1.0f, 1.0f, 0.5f);
        scale.setDuration(duration);
        scale.setFillAfter(true);

        // 旋转动画
        RotateAnimation rotate = new RotateAnimation(0f, 260f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setDuration(duration);
        rotate.setFillAfter(true);

        // 集合动画
        setAnim = new AnimationSet(true);
        setAnim.addAnimation(alpha);
        setAnim.addAnimation(translate);
        setAnim.addAnimation(scale);
        setAnim.addAnimation(rotate);
        setAnim.setFillAfter(true);
        view.startAnimation(setAnim);
        setAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 开始播放动感影集
     */
    private void playYingji() {
        picChoiceRl.removeAllViews();
        initView();                 // 初始化各视图

        picChoiceRl.addView(view1, 0);
        anim1 = ObjectAnimator.ofFloat(view1, "alpha", 0.1f, 1.0f);
        anim1.setDuration(duration);
        anim1.addListener(this);
        anim1.start();
    }

    /**
     * 初始化各视图
     */
    private void initView() {
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        view1 = getImageView(params, imageArray.get(0));

        // 百叶窗视图
        view2 = new ShutterView(this);
        view2.setLayoutParams(params);
        view2.setBitmap(BitmapFactory.decodeResource(getResources(), imageArray.get(1)));
        view2.setMode(PorterDuff.Mode.DST_OUT);

        // 马赛克视图
        view3 = new MosaicView(this);
        view3.setLayoutParams(params);
        view3.setBitmap(BitmapFactory.decodeResource(getResources(), imageArray.get(2)));
        view3.setMode(PorterDuff.Mode.DST_OUT);

        view4 = getImageView(params, imageArray.get(3));
        view5 = getImageView(params, imageArray.get(4));
        view6 = getImageView(params, imageArray.get(5));
    }

    private ImageView getImageView(ViewGroup.LayoutParams params, int imageId) {
        ImageView imageView = new ImageView(this);
        imageView.setLayoutParams(params);
        imageView.setImageResource(imageId);
        return imageView;
    }

    /**

     // 初始化补间动画
     private void initTweenAnim() {
     // 创建一个灰度动画，从完全透明变为即将不透明
     alphaAnim = new AlphaAnimation(1.0f, 0.1f);
     alphaAnim.setDuration(3000);
     alphaAnim.setFillAfter(true); // 是否维持结束画面

     // 创建一个平移动画，向左平移 100 dp
     translateAnim = new TranslateAnimation(1.0f, -100, 1.0f, 1.0f);
     translateAnim.setDuration(3000);
     translateAnim.setFillAfter(true);

     // 创建一个缩放动画，宽度不变，高度变为原来的二分之一
     scaleAnim = new ScaleAnimation(1.0f, 1.0f, 1.0f, 0.5f);
     scaleAnim.setDuration(3000);
     scaleAnim.setFillAfter(true);

     // 创建一个旋转动画，围绕着圆心顺时针旋转 360°
     rotateAnim = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
     rotateAnim.setDuration(3000);
     rotateAnim.setFillAfter(true);
     }

     // 播放指定类型的补间动画
     private void playTweenAnim(int type) {
     if (type == 1) {
     tweenAnimIv.startAnimation(alphaAnim);
     alphaAnim.setAnimationListener(this);
     } else if (type == 2) {
     tweenAnimIv.startAnimation(translateAnim);
     translateAnim.setAnimationListener(this);
     } else if (type == 3) {
     tweenAnimIv.startAnimation(scaleAnim);
     scaleAnim.setAnimationListener(this);
     } else if (type == 4) {
     tweenAnimIv.startAnimation(rotateAnim);
     rotateAnim.setAnimationListener(this);
     }
     }

     @Override public void onAnimationStart(Animation animation) {

     }

     @Override public void onAnimationEnd(Animation animation) {
     if (animation.equals(alphaAnim)) {
     // 创建一个灰度动画，从即将不透明变为完全透明
     AlphaAnimation alphaAnim2 = new AlphaAnimation(0.1f, 1.0f);
     alphaAnim2.setDuration(3000);
     alphaAnim2.setFillAfter(true);
     tweenAnimIv.startAnimation(alphaAnim2);
     } else if (animation.equals(translateAnim)) {
     // 创建一个平移动画，向右平移 100dp
     TranslateAnimation translateAnim2 = new TranslateAnimation(-100, 1.0f, 1.0f, 1.0f);
     translateAnim2.setDuration(3000);
     translateAnim2.setFillAfter(true);
     tweenAnimIv.startAnimation(translateAnim2);
     } else if (animation.equals(scaleAnim)) {
     ScaleAnimation scaleAnim2 = new ScaleAnimation(1.0f, 1.0f, 0.5f, 1.0f);
     scaleAnim2.setDuration(3000);
     scaleAnim2.setFillAfter(true);
     tweenAnimIv.startAnimation(scaleAnim2);
     } else if (animation.equals(rotateAnim)) {
     RotateAnimation rotateAnim2 = new RotateAnimation(0f, -360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
     rotateAnim2.setDuration(3000);
     rotateAnim2.setFillAfter(true);
     tweenAnimIv.startAnimation(rotateAnim2);
     }
     }

     @Override public void onAnimationRepeat(Animation animation) {

     }

     // // 显示 GIF 动图
     // private void showGifAnimationOld(int imageId) {
     //     // 从源文件中获取输入流对象
     //     InputStream is = getResources().openRawResource(imageId);
     //     GifImage gifImage = new GifImage(); // 创建一个 GIF 图像对象
     //     int code = gifImage.read(is);       // 从输入流中读取 GIF 数据
     //     if (code == GifImage.STATUS_OK) {   // 读取成功
     //         GifImage.GifFrame[] frameList = gifImage.getFrames();
     //         AnimationDrawable adGif = new AnimationDrawable();
     //         for (GifImage.GifFrame frame : frameList) {
     //             BitmapDrawable drawable = new BitmapDrawable(getResources(), frame.image);
     //             adGif.addFrame(drawable, frame.delay);
     //         }
     //         adGif.setOneShot(false);
     //         gifIv.setImageDrawable(adGif);
     //         adGif.start();
     //     } else if (code == GifImage.STATUS_FORMAT_ERROR) {
     //         Toast.makeText(this, "该图片不是 gif 格式", Toast.LENGTH_SHORT).show();
     //     } else {
     //         Toast.makeText(this, "gif 图片读取失败", Toast.LENGTH_SHORT).show();
     //     }
     // }
     **/
}